package com.mywind.inteceptor.core;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.mywind.entity.core.User;


/**
 * Created by A01162 on 2014/11/04.
 */
public class LoginInteceptor implements HandlerInterceptor{
	//不对匹配该值的访问路径拦截（正则）
	public static final String NO_INTERCEPTOR_PATH = ".*/((login)|(logout)|(toLogin)).*";
	
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        String contextPath = request.getContextPath();
        String servletPath = request.getServletPath();
        
        if (servletPath.equals("/")) {
            response.sendRedirect(contextPath + "user/toLogin.do");
            return false;
        }

        //这里指如果ServletPath是/user/reg.do的话就不执行拦截。下面同理。
//        if (servletPath.equals("/reg.do")) {
//            return true;
//        }
//        if (servletPath.equals("/validateUsername.do")) {
//            return true;
//        }
        if(servletPath.matches(NO_INTERCEPTOR_PATH)){
			return true;
		}else{
            User mysession = (User) session.getAttribute("mysession");
            if (mysession == null) {
                response.sendRedirect(contextPath + "/user/toLogin.do");
                return false;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
